<?php

namespace addons\yiliao\controller\api;

use app\admin\model\yiliao\Order as OrderModel;
use app\admin\model\yiliao\Pro;
use app\admin\model\yiliao\Usercoupon;
use app\admin\model\yiliao\Promotion;
use app\admin\model\yiliao\User;
use app\admin\model\yiliao\Log as LogModel;
use app\admin\model\yiliao\Booking;
use app\admin\model\yiliao\Shop;

use think\Db;
use fast\Http;
use think\Log;

class Order extends Base
{
    public function _initialize()
    {
        parent::_initialize();
    }

    public function myorder_refund()
    {
        $orderid = $this->request->param("orderid");
        $order =OrderModel::where(['orderid'=>$orderid,'yiliao_user_id'=>$this->user['userid']])->find();
        if ($order['status'] == 1) {
            $res = OrderModel::where(['orderid'=>$orderid,'yiliao_user_id'=>$this->user['userid']])->update(['status'=>3]);
            if ($res) {
                $this->success('退款审核中');
            } else {
                $this->error('退款失败');
            }
        } else {
            $this->error("禁止退款");
        }
    }
    public function retopay()
    {
        $paytype = $this->request->param("paytype");
        $orderid = $this->request->param("orderid");
        $neworderid = date("YmdHis").rand(100, 999);
        $order =OrderModel::where(['orderid'=>$orderid,'yiliao_user_id'=>$this->user['userid']])->find();
       
        $auth_code = rand(1000, 9999);
        OrderModel::where(['orderid'=>$orderid,'yiliao_user_id'=>$this->user['userid']])->update(['orderid'=>$neworderid]);
        $params = [
            'amount'=>$order['total'],
            'orderid'=>$neworderid,
            'type'=>'wechat',
            'title'=>"订单".$neworderid,
            'notifyurl'=>$this->apiurl.'/addons/yiliao/api.order/notify',
            'returnurl'=>$this->apiurl.'/addons/yiliao/api.order/notify',
            'method'=>$paytype,
            'openid'=>$this->user['openid'],
            'auth_code'=>$auth_code
        ];
        
        $data= \addons\epay\library\Service::submitOrder($params);
      
        $this->success('success', $data);
    }

    public function delorder()
    {
        $orderid = $this->request->param('orderid');
        $res = OrderModel::where(['orderid'=>$orderid,'yiliao_user_id'=>$this->user['userid']])->delete();
        if ($res) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

	public function couponhexiao(){
		$id = $this->request->param('id');
		$row=[];
		if($this->user){
			//先看是不是核销员
			$user = User::where(['id'=>$this->user['userid']])->find();
			if($user['coupondata']){
				$row = Usercoupon::where(['id'=>$id])->find();
				$row['islogin']=1;
				
				if ($row['status'] == "hidden") {
					$res = Usercoupon::where(['id'=>$id])->update(['status'=>'normal', 'hxuserid'=>$this->user['userid'], 'hxtime'=>date("Y-m-d H:i:s")]);
					if ($res) {
						//$this->success('核销成功',$row);
					} else {
						$this->error('核销失败');
					}
				} else {
					$this->error("失败:请勿重复核销");
				}
				
			} else {
				$this->error("您不是优惠券核销员");
			}
		} else {
			$row['islogin']=0;
		}
		$this->success('', $row);
	}
	
	public function orderhexiao(){
		$orderid = $this->request->param('orderid');
		$row=[];
		if($this->user){
			//先看是不是核销员
			$user = User::where(['id'=>$this->user['userid']])->find();
			if($user['orderdata']){
				$row = OrderModel::where(['orderid'=>$orderid])->find();
				$row['islogin']=1;
				 //计算总价
				$row['zongjia'] = sprintf("%.2f", $row['total']+$row['coupon']);
				$row['time'] = date("Y-m-d H:i:s", $row['createtime']);
				$row['image'] = cdnurl($row['image'], true);
				//直接报核销成功
				if ($row['status']==1) {
					OrderModel::where(['orderid'=>$orderid])->update(['status'=>2, 'hxuserid'=>$this->user['userid'], 'hxtime'=>date("Y-m-d H:i:s")]);
				}else {
					$this->error("失败:请勿重复核销");
				}
				
			} else {
				$this->error("您不是订单核销员");
			}
		} else {
			$row['islogin']=0;
		}
		$this->success('', $row);
	}
    public function orderdetail()
    {
        $orderid = $this->request->param('orderid');
        $isxcx = $this->request->param('isxcx');
        $row = OrderModel::where(['orderid'=>$orderid,'yiliao_user_id'=>$this->user['userid']])->find();
        //计算总价
        $row['zongjia'] = sprintf("%.2f", $row['total']+$row['coupon']);
        $row['time'] = date("Y-m-d H:i:s", $row['createtime']);
        $row['image'] = cdnurl($row['image'], true);

        //生成二维码
        ///www/wwwroot/xx/public
		if($isxcx==1){
			$document_path = request()->server('DOCUMENT_ROOT');
			$path = '/uploads/yiliao/'.md5($row["id"].$row['orderid']).'.jpg';
			if (!file_exists($document_path.$path)) {
				$access = $this->getaccess();
				$api = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access['access_token'];
				$can = [];
				$can['page']='pages/index/index';
				$can['scene']="orderid=".$row['id'];
				$can['check_path']=false;
				$can['auto_color']=false;
				$can['width']=430;
				//$can['env_version']='develop';
				$res = Http::post($api, json_encode($can));

				if (!is_dir($document_path.'/uploads/yiliao')) {
					mkdir(iconv("UTF-8", "GBK", $document_path.'/uploads/yiliao'), 0777, true);
				}
				$file = fopen($document_path.$path, "w");//创建件准备写入
				fwrite($file, $res);//写入
				fclose($file);//关闭
			}
			$row['ewm']=$this->apiurl.$path;
		} else {
			$info = get_addon_info('qrcode');
            if (!$info|| !$info['state']) {
                $this->error('请确保二维码生成插件已安装并启用');
            } else {
				$url = $this->apiurl.'/#/pages/user/myorderuse/hexiao?orderid='.$orderid;
				$row['ewm']=$this->apiurl.'/qrcode/build?text='.urlencode($url);
			}
		}
        
        $this->success('', $row);
    }

    /**
     * 状态:0=待付款,1=待服务,2=已完成,3=退款中,4=已退款
     */
    public function myorder()
    {
        $status = $this->request->param('status');
        $keyword = $this->request->param('keyword');
        $page = $this->request->param('page',1);
        $where=[];
        $where['yiliao_user_id'] = $this->user['userid'];
        if ($status==0||$status==1||$status==2) {
            $where['status']=$status;
        } elseif ($status==3) {
            $where['status']=['in','3,4'];
        }
        if ($keyword) {
            $where['name'] = ['like',"%$keyword%"];
        }
        $rows=OrderModel::where($where)->order("id desc")->field("id,orderid,name,image,shopname,catename,price,status,num,total")->page($page,10)->select();
        foreach ($rows as $k => $v) {
            $rows[$k]['image'] = cdnurl($v['image'], true);
            if ($v['status'] ==1) {
                $rows[$k]['txt']='待服务';
            } elseif ($v['status']==2) {
                $rows[$k]['txt']='已完成';
            } elseif ($v['status']==3) {
                $rows[$k]['txt']='退款中';
            } elseif ($v['status']==4) {
                $rows[$k]['txt']='已退款';
            } else {
                $rows[$k]['txt']='待付款';
            }
        }
        $this->success('', $rows);
    }

    public function topay()
    {
        Db::startTrans();
        try {
            $info = get_addon_info('epay');
            if (!$info|| !$info['state']) {
                $this->error('请确保微信支付宝整合插件已安装并启用');
            }
            $paytype = $this->request->param('paytype');
            $id = $this->request->param('id');
            $hdid = $this->request->param('hdid');
            $couponid = $this->request->param('couponid');
            $isshop = $this->request->param('isshop');
            $shopid = $this->request->param('shopid');

            if ($hdid>0) {
                $huodong = Promotion::where(['id'=>$hdid])->find();
                //join("yiliao_shop S", "A.yiliao_shop_id=S.id")->
                $row = Pro::alias("A")->join("yiliao_procate C", "A.yiliao_procate_id=C.id")->where(['A.id'=>$huodong['yiliao_pro_id']])->field("A.*,C.name as catename")->find();
                if ($isshop==1) {
                    $shop = Shop::where(['id'=>$shopid])->find();
                    $row['shopname']=$shop['name'];
                } else {
                    $shop = Shop::where(['id'=>['in',$row['yiliao_shop_ids']],'status'=>1])->order("id desc")->find();
                    $row['shopname']=$shop['name'];
                }
                $row['price']=$huodong['price'];
            } else {
                $row = Pro::alias("A")->join("yiliao_procate C", "A.yiliao_procate_id=C.id")->where(['A.id'=>$id])->field("A.*,C.name as catename")->find();
                
                if ($isshop==1) {
                    $shop = Shop::where(['id'=>$shopid])->find();
                    $row['shopname']=$shop['name'];
                } else {
                    $shop = Shop::where(['id'=>['in',$row['yiliao_shop_ids']],'status'=>'normal'])->order("id desc")->find();
                    $row['shopname']=$shop['name'];
                }
            }
            
            $date=date("Y-m-d");
            $coupon = Usercoupon::where(['status'=>'hidden','id'=>$couponid,'start'=>['elt',$date],'end'=>['egt',$date]])->find();
            
            if ($couponid>0 && $coupon) {
                $total=$row['price']-$coupon['price'];
                if ($total>0) {
                    $dikou=$coupon['price'];
                } else {
                    $dikou = $row['price'];
                }
            } else {
                $total=$row['price'];
                $dikou=0;
            }
            if ($total<0) {
                $total=0;
            }
            $orderid = date("YmdHis").rand(100, 999);
            $auth_code = rand(1000, 9999);

            $d=[];
            $d['createtime']=time();
            $d['orderid']=$orderid;
            $d['yiliao_user_id']=$this->user['userid'];
            $d['name']=$row['name'];
            $d['image']=$row['image'];
            $d['shopname']=$row['shopname'];
            $d['catename']=$row['catename'];
            $d['total'] = sprintf("%.2f", $total);
            $d['price']=$row['price'];
            $d['jifen']=$row['jifen'];
            $d['num']=1;
            $d['couponid']=$couponid;
            //优惠券抵扣
            $d['coupon']=$dikou;
            $d['hdid']=$hdid;
            $ret=[];
            if ($total>0) {
                $d['paytime']=0;
                $d['status']=0;
                $res = OrderModel::insert($d);
                $params = [
                    'amount'=>$total,
                    'orderid'=>$orderid,
                    'type'=>'wechat',
                    'title'=>"订单".$orderid,
                    'notifyurl'=>$this->apiurl.'/addons/yiliao/api.order/notify',
                    'returnurl'=>$this->apiurl.'/addons/yiliao/api.order/notify',
                    'method'=>$paytype,
                    'openid'=>$this->user['openid'],
                    'auth_code'=>$auth_code
                ];
                $data= \addons\epay\library\Service::submitOrder($params);
                //print_r($data);
                
                $ret['timeStamp'] = $data['timeStamp'];
                $ret['nonceStr'] = $data['nonceStr'];
                $ret['package'] = $data['package'];
                $ret['paySign'] = $data['paySign'];
                $ret['appId'] = $data['appId'];
                $ret['signType'] = $data['signType'];
                $ret['status']=0;
                
                //$this->success('success',$ret);
            } else {
                $d['paytime']=time();
                $d['status']=1;
                $ret['status']=1;
                $res = OrderModel::insert($d);
                if ($res) {
                    if ($couponid>0) {
                        Usercoupon::where(['id'=>$couponid])->update(['status'=>'normal','updatetime'=>time()]);
                    }
                } else {
                    $this->error('支付失败');
                }
            }

            Db::commit();
            $this->success('支付成功', $ret);
        } catch (\think\exception\ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\think\exception\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\think\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
    
    public function notify()
    {
        $paytype = $this->request->param('paytype');
        $paytype='wechat';
        $pay = \addons\epay\library\Service::checkNotify($paytype);
        Log::record($pay, 'notice');
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = $pay->verify();
        Log::record($data, 'notice');
        try {
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $orderid = $data['out_trade_no'];
            $order =OrderModel::where('orderid', $orderid)->find();
            if ($order['status'] == '0') {
                OrderModel::where('orderid', $orderid)->update(['status'=>1,'paytime'=>time()]);
                if ($order['couponid'] > 0) {
                    Usercoupon::where(['id'=>$order['couponid']])->update(['status'=>'normal','updatetime'=>time()]);
                }

                if ($order['jifen']>0) {
                    $setting = $this->setting;
                    $parent = UserModel::where(['id'=>$order['yiliao_user_id']])->find();
                    //送积分
                    $log=[];
                    $log['createtime']=time();
                    $log['yiliao_user_id']=$order['yiliao_user_id'];
                    $log['name']="购买商品送积分".$orderid;
                    $log['point']=$order['jifen'];
                    $total = $order['jifen']+$parent['jifen'];
                    $log['total']=$total;
                    $log['type']=2;
                    LogModel::insert($log);
                    User::where(['id'=>$order['yiliao_user_id']])->update(['jifen'=>$total]);
                }
                echo $pay->success();
            }
            //你可以在此编写订单逻辑
        } catch (\think\Exception $e) {
        }
    }
    public function bookingnotify()
    {
        $paytype = $this->request->param('paytype');
        $paytype='wechat';
        $pay = \addons\epay\library\Service::checkNotify($paytype);
        Log::record($pay, 'notice');
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = $pay->verify();
        Log::record($data, 'notice');
        try {
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $orderid = $data['out_trade_no'];
            $order =Booking::where('orderid', $orderid)->find();
            if ($order['status'] == '0') {
                Booking::where('orderid', $orderid)->update(['status'=>1,'createtime'=>time()]);
                echo $pay->success();
            }
            //你可以在此编写订单逻辑
        } catch (\think\Exception $e) {
        }
    }
}
